<?php
/** 初始化项目 */
namespace app\api;

use app\Controller;
use app\util\Mysql;
use tinymeng\tools\Strings;

class Upload extends Controller
{

    public $uploadOk = 1;//设置文件上传初始状态为 OK
    public $error;

    /**
     * @return null
     */
    public function index()
    {
        $type = $_POST['mode'] ?? null;
        switch ($type) {
            case 'editor':
                return $this->editor();
            case 'layui':
                return $this->layui();
            default;
        }
        return error();
    }


    /**
     * 富文本上传文件
     * @return void
     */
    public function editor()
    {
        if (empty($_FILES['file'])) {
            $this->editorJsonReturn(1, '上传的文件不能为空');
        }

        if (!empty($_POST['type']) && $_POST['type'] == 'video') {
            $allowTypes = ['mp4', 'flv'];
            $size = 50;//视频限制50兆
        } else {
            $allowTypes = ['jpg', 'png', 'jpeg', 'gif'];
            $size = 5;//图片限制5兆
        }
        //获取上传信息
        $file = $_FILES['file'];
        $url = $this->upload($file, 'editor', $size, $allowTypes);
        if (empty($url)) {
            $this->editorJsonReturn(1, $this->error);
        }

        $filename = $file["name"];
        $this->editorJsonReturn(0, '', [
            'url' => $url,
            'alt' => $filename,
        ]);
    }

    /**
     * 富文本上传文件
     * @return void
     */
    public function layui()
    {
        if (empty($_FILES['file'])) {
            $this->editorJsonReturn(1, '上传的文件不能为空');
        }

        if (!empty($_POST['type']) && $_POST['type'] == 'zip') {
            $allowTypes = ['zip', 'rar', '7z'];
            $size = 50;//视频限制50兆
        } else {
            $allowTypes = ['jpg', 'png', 'jpeg', 'gif'];
            $size = 5;//图片限制5兆
        }
        //获取上传信息
        $file = $_FILES['file'];
        $url = $this->upload($file, 'editor', $size, $allowTypes);
        if (empty($url)) {
            $this->layuiJsonReturn(1, $this->error);
        }

        $filename = $file["name"];
        $this->layuiJsonReturn(0, '', [
            'src' => $url,
            'alt' => $filename,
        ]);
    }

    /**
     * @param $file
     * @param $file_path
     * @param $size
     * @param $allowTypes
     */
    public function upload($file, $file_path, $size = 5, $allowTypes = ['jpg', 'png', 'jpeg', 'gif'])
    {
        $path_name = "/upload/" . $file_path . '/' . date('Y-m-d') . '/'; // 目录名称
        $target_dir = PUBLIC_PATH . $path_name; // 上传目录
        $imageFileType = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION)); // 获取文件扩展名
        $file_name = Strings::generateRandomString(15) . '.' . $imageFileType;
        $target_file = $target_dir . $file_name; // 目标文件路径

        // 检查目录是否存在
        if (!is_dir($target_dir)) {
            mkdir($target_dir, 0777, true); // 如果目录不存在则创建它
        }

        // 检查文件是否已经存在
        if (file_exists($target_file)) {
            $this->error = "Sorry, file already exists.";
            $this->uploadOk = 0;
        }

        // 限制文件大小（这里设置为 5MB）
        if ($file["size"] > $size * 1024 * 1024) {
            echo "Sorry, your file is too large.";
            $this->uploadOk = 0;
        }

        // 允许特定文件格式
        if (!empty($allowTypes) && !in_array($imageFileType, $allowTypes)) {
            $this->error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            $this->uploadOk = 0;
        }

        // 如果 $uploadOk 为真，则尝试移动文件
        if ($this->uploadOk == 1) {
            $file_hash = md5_file($file['tmp_name']);
            $res = $this->move($file, $target_file);
            if ($res) {
                $url = '/public' . $path_name . $file_name;

                //存储到文件库
                $data = [
                    'user_id' => $this->userInfo['id']??0,
                    'file_name' => $file['name'],
                    'file_size' => $file["size"],
                    'file_hash' => $file_hash,
                    'file_url' => $url,
                    'create_time' => NOW_TIME,
                    'text_id' => $_POST['text_id'] ?? '',
                ];
                $this->saveFile($data);
                return $url;//拼接路径
            } else {
                $this->error = "Sorry, there was an error uploading your file.";
            }
        }
        return false;
    }

    /**
     * @param $file
     * @param $target_file
     * @return bool
     */
    public function move($file, $target_file)
    {
        return move_uploaded_file($file["tmp_name"], $target_file);
    }

    /**
     * @param $code
     * @param $message
     * @param $data
     * @return void
     */
    public function editorJsonReturn($code, $message = '', $data = '')
    {
        header('Content-Type: application/json');
        exit(json_encode([
            'errno' => $code,
            'message' => $message,
            'data' => $data,
        ]));
    }

    /**
     * @param $code
     * @param $message
     * @param $data
     * @return void
     */
    public function layuiJsonReturn($code, $message = '', $data = '')
    {
        header('Content-Type: application/json');
        exit(json_encode([
            'code' => $code,
            'msg' => $message,
            'data' => $data,
        ]));
    }

    /**
     * @param $data
     * @return void
     */
    public function saveFile($data)
    {
        /** 初始化数据库 */
        $database = Mysql::init();
        $database->insert("more_file", $data);
    }
}